<?php

defined('IN_TS') or die('Access Denied.'); 
require_once("config.php");


if($_REQUEST['code']){
    $weixinJsonOpen = curl_get_file_contents('https://api.weixin.qq.com/sns/oauth2/access_token?appid='.WX_AKEY.'&secret='.WX_SKEY.'&code='.$_REQUEST['code'].'&grant_type=authorization_code');
    $weixinOpen = json_decode($weixinJsonOpen,true);
    $openid = $weixinOpen['openid'];
	$unionid =  $weixinOpen['unionid'];


    $access_token = $weixinOpen['access_token'];

}else{
    exit;
}



if ($openid) {
	
	$strOpen = $new['pubs']->find('user_open',array(
		'sitename'=>'weixin',
		'openid'=>$unionid,
	));
	
	//10天更换一次access_token
	if(time()-10*86400>$strOpen['uptime']){
		$new['pubs']->update('user_open',array(
			'sitename'=>'weixin',
			'openid'=>$unionid,
		),array(
			'access_token'=>$access_token,
			'uptime'=>time(),
		));
	}
	
	
	if($strOpen['userid']){
		
		$userData = $new['pubs']->find('user_info',array(
			'userid'=>$strOpen['userid'],
		),'userid,username,path,face,isadmin,signin,uptime,follow_uid,idcard,wxopenid,phone,unit');
		
		//更新登录时间
		$new['pubs']->update('user_info',array(
			'userid'=>$strOpen['userid'],
		),array(
			'ip'=>getIp(),  //更新登录ip
			'uptime'=>time(),   //更新登录时间
		));
		
		$_SESSION['tsuser']	= $userData;
		header("Location: ".SITE_URL);
		exit;
		
	}else{
	
		//获取用户基本资料

        $userInfoJson = curl_get_file_contents('https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid);

        $arrUserInfo = json_decode($userInfoJson,true);


		switch($arrUserInfo['sex']){
			case 0:
				$sex='保密';
				break;
			case 1:
				$sex='男';
				break;
			case 2:
				$sex='女';
				break;
		}

        //print_r($arrUserInfo);exit;

        //Array ( [openid] => ovU5Ht8W2nSJAtne7Sh_lFTPgqbo [nickname] => 奇鸟软件 [sex] => 1 [language] => zh_CN [city] => Chaoyang [province] => Beijing [country] => CN [headimgurl] => http://wx.qlogo.cn/mmopen/ajNVdqHZLLA8w9to0lYibud6XUv7xvUDBe7TtfguzArsg5iakozctWbRJK5DAYF1MKJmwYZ47jfzEHvoxO6Lia5RA/0 [privilege] => Array ( ) [unionid] => oCtnrsgXPRNvw1Tm8etYPC0NWPyQ )

		$salt = md5(rand());

		$pwd = random(5,0);

		$userid = $new['pubs']->create('user',array(
			'pwd'=>md5($salt.$pwd),
			'salt'=>$salt,
			'email'=>$unionid,
		));

		//插入ts_user_info
		$new['pubs']->create('user_info',array(
			'userid'			=> $userid,
			'username' 	=> $arrUserInfo['nickname'],
			'email'		=> $unionid,
			'sex'=> $sex,
			'ip'			=> getIp(),
			'addtime'	=> time(),
			'uptime'	=> time(),
		));

		//插入ts_user_open
		$new['pubs']->create('user_open',array(
			'userid'=>$userid,
			'sitename'=>'weixin',
			'openid' => $unionid,
			'access_token'=>$access_token,
			'uptime'=>time(),
		));

		//更新用户头像
		if($arrUserInfo['headimgurl']){
			//1000个图片一个目录
			$menu2=intval($userid/1000);
			$menu1=intval($menu2/1000);
			$menu = $menu1.'/'.$menu2;
			$photo = $userid.'.jpg';

			$photos = $menu.'/'.$photo;

			$dir = 'uploadfile/user/'.$menu;

			$dfile = $dir.'/'.$photo;

			createFolders($dir);

			if(!is_file($dfile)){
				$img = file_get_contents($arrUserInfo['headimgurl']);
				file_put_contents($dfile,$img);
			};

			$new['pubs']->update('user_info',array(
				'userid'=>$userid,
			),array(
				'path'=>$menu,
				'face'=>$photos,
			));

		}

		//获取用户信息
		$userData = $new['pubs']->find('user_info',array(
			'userid'=>$userid,
		),'userid,username,path,face,isadmin,signin,uptime,follow_uid,idcard,wxopenid,phone,unit');


		//发送系统消息(恭喜注册成功)
		$msg_userid = '0';
		$msg_touserid = $userid;
		$msg_content = '亲爱的微信用户 '.$username.' ：您成功加入了 '
									.$TS_SITE['site_title'].'在遵守本站的规定的同时，享受您的愉快之旅吧!';
		aac('message')->sendmsg($msg_userid,$msg_touserid,$msg_content);

		$_SESSION['tsuser']	= $userData;

		header("Location: ".SITE_URL);
		exit;
	}
	
	
} 
